package com.example.jimmerfast.controller;

import cn.hutool.core.util.StrUtil;
import com.example.jimmerfast.entity.*;
import com.example.jimmerfast.entity.dto.RoleSpecification;
import com.example.jimmerfast.entity.dto.UserInput;
import com.example.jimmerfast.entity.dto.UserSpecification;
import com.example.jimmerfast.service.RoleService;
import com.example.jimmerfast.shape.RoleShape;
import com.example.jimmerfast.shape.UserShape;
import com.example.jimmerfast.util.PageParam;
import com.example.jimmerfast.util.PageResult;
import lombok.RequiredArgsConstructor;
import org.babyfish.jimmer.client.FetchBy;
import org.babyfish.jimmer.sql.ast.query.ConfigurableRootQuery;
import org.babyfish.jimmer.sql.ast.query.Example;
import org.babyfish.jimmer.sql.ast.table.spi.TableProxy;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequiredArgsConstructor
@RequestMapping("role")
public class RoleController {

    private final RoleService roleService;


    @GetMapping("list")
    public List<Role> list(RoleSpecification roleSpecification) {
        return roleService.query().where(RoleTable.$.eq(roleSpecification.toEntity())).
                whereIf(roleSpecification.getUserId() != null,
                        RoleTable.$.asTableEx().users().id()
                                .eq(roleSpecification.getUserId()))
                .select(RoleTable.$)
                .distinct().execute();
    }

    @GetMapping("page")
    public PageResult<@FetchBy(value = "ALL_SCALAR", ownerType = RoleShape.class) Role> page(PageParam pageParam, RoleSpecification specification) {
        ConfigurableRootQuery<? extends TableProxy<Role>, Role> query = roleService.query().
                whereIf(StrUtil.isNotBlank(specification.getName()), RoleTable.$.name().like(specification.getName()))
                .select(RoleTable.$.fetch(RoleShape.ALL_SCALAR));
        return roleService.page(pageParam, query);
    }

    @PostMapping("authorize")
    public void authorize(@RequestParam Long roleId, @RequestBody List<Long> resourceIds) {
       roleService.authorize(roleId, resourceIds);
    }

    @PostMapping("deleteByIds")
    public void deleteByIds(@RequestBody List<Long> ids) {
        roleService.deleteByIds(ids);
    }
}
